/*
 * Copyright (c) 2024 endless-sky
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#pragma once

#include <nlohmann/json.hpp>
#include <string>
#include <memory>
#include <mutex>
#include <thread>
#include <atomic>
#include <inttypes.h>

namespace El {
namespace SystemService {
/**
 * @brief 看门狗管理器单例类
 */
class WatchdogManager {
public:
    /**
     * @brief 获取单例实例
     * @return WatchdogManager& 单例实例引用
     */
    static WatchdogManager &GetInstance();

    /**
     * @brief 启动看门狗并应用配置
     * @return true 成功，false 失败
     */
    bool Start();

    /**
     * @brief 喂狗操作
     * @return true 成功，false 失败
     */
    bool Feed();

    /**
     * @brief 停止看门狗
     * @return true 成功，false 失败
     */
    bool Stop();

    /**
     * @brief 获取当前看门狗状态
     * @return true 已启动，false 未启动
     */
    bool IsRunning() const;

    /**
     * @brief 获取看门狗超时时间
     * @return int32_t 超时时间（秒）
     */
    int32_t GetTimeout() const;

private:
    // 私有构造函数，防止外部创建实例
    WatchdogManager();

    // 禁用拷贝构造和赋值操作符
    WatchdogManager(const WatchdogManager &) = delete;
    WatchdogManager &operator=(const WatchdogManager &) = delete;

    // 析构函数
    ~WatchdogManager();

    // 喂狗线程函数
    void FeedThread();

    // 超时时间（秒）
    int32_t timeoutSeconds_;
    // 运行状态
    std::atomic<bool> isRunning_;
    // 互斥锁，保护并发访问
    mutable std::mutex mutex_;
    // 喂狗线程
    std::thread feedThread_;
};

} // namespace SystemService
} // namespace El